package com.csun.cmny.security.core.authentication;

import com.csun.cmny.security.core.properties.SecurityConstants;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Auther: chisj chisj@foxmal.com
 * @Date: 2021-01-18 19:48
 * @Description:
 */
public class WeiXinAuthenticationFilter extends AbstractAuthenticationProcessingFilter {

    private static final String POST = "POST";
    private boolean postOnly = true;

    /**
     * 配置自定义微信登录接口
     */
    public WeiXinAuthenticationFilter() {
        super(new AntPathRequestMatcher(SecurityConstants.DEFAULT_SIGN_IN_PROCESSING_URL_WX, "POST"));
    }

    /**
     * Attempt authentication authentication.
     *
     * @param request  the request
     * @param response the response
     *
     * @return the authentication
     *
     * @throws AuthenticationException the authentication exception
     */
    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
            throws AuthenticationException {
        if (postOnly && !POST.equals(request.getMethod())) {
            throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
        }

        String code = request.getParameter("code");
        String nickName = request.getParameter("nickName");
        String avatar = request.getParameter("avatar");
        String gender = request.getParameter("gender");
        String city = request.getParameter("city");
        String application = request.getParameter("application");

        WeiXinAuthenticationToken authRequest = new WeiXinAuthenticationToken(code, nickName, avatar, gender, city);

        // Allow subclasses to set the "details" property
        setDetails(request, authRequest);

        return this.getAuthenticationManager().authenticate(authRequest);
    }

    protected void setDetails(HttpServletRequest request, WeiXinAuthenticationToken authRequest) {
        authRequest.setDetails(authenticationDetailsSource.buildDetails(request));
    }

}
